﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;

namespace CarDriver
{
    class server_client
    {
        const int TIMEOUT_MILLISECONDS = 5000;
        Socket socket_ = null;
        static ManualResetEvent _clientDone = new ManualResetEvent(false);
        
        public server_client()
        {
           
           DnsEndPoint hostEntry = new DnsEndPoint("192.168.0.101", 6669);
           socket_ = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
           SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
           socketEventArg.RemoteEndPoint = hostEntry;

           socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
           {
               // Signal that the request is complete, unblocking the UI thread
               _clientDone.Set();
           });

           // Sets the state of the event to nonsignaled, causing threads to block
           _clientDone.Reset();

           // Make an asynchronous Connect request over the socket
           socket_.ConnectAsync(socketEventArg);

           // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
           // If no response comes back within this time then proceed
     ///      _clientDone.WaitOne(TIMEOUT_MILLISECONDS);
       }

        public void send(message msg)
        {
            if (socket_ != null)
            {
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();

                // Set properties on context object
                socketEventArg.RemoteEndPoint = socket_.RemoteEndPoint;
                socketEventArg.UserToken = null;

                // Inline event handler for the Completed event.
                // Note: This event handler was implemented inline in order 
                // to make this method self-contained.
                socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
                {
                    // Unblock the UI thread
                    _clientDone.Set();
                });

                socketEventArg.SetBuffer(msg.get(), 0, msg.size());

                // Sets the state of the event to nonsignaled, causing threads to block
                _clientDone.Reset();

                // Make an asynchronous Send request over the socket
                socket_.SendAsync(socketEventArg);

                // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
                // If no response comes back within this time then proceed
             //   _clientDone.WaitOne(TIMEOUT_MILLISECONDS);
            }
        }
    }
}
